﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Data.SqlClient;
using System.Data;

namespace MyLibary
{
    class DAL_Connection
    {
        public string Host { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public SqlConnection Connection = null;
        public DAL_Connection()
        {
            this.Connection = new SqlConnection(@"Data Source=ASUS-PC\SQLEXPRESS;Database=DongHo;Integrated Security=true");
        }
        /// <summary>
        /// Open connection
        /// </summary>
        /// <returns>boolean( return true- if connect is successfull ;return false if connect is fail</returns>
        public bool Open()
        {
            try
            {
                Connection.Open();
            }
            catch { return false; }
            return true;
        }
        /// <summary>
        /// thực hiện câu truy vấn làm thay đổi CSDL như Insert,Update,Delete
        /// </summary>
        /// <param name="query">câu truy vấn</param>
        /// <returns>trả true nếu thực hiện thành công ngược lại trả về false</returns>
        public bool ExecuteUpdate(string query)
        {
            bool result;
            if (!this.Open())
                return false;
            SqlCommand cmd = new SqlCommand(query, Connection);
           result = cmd.ExecuteNonQuery() > 0;
         
            Connection.Close();
            return result;
        }
        /// <summary>
        /// thực thi câu truy vấn Select
        /// </summary>
        /// <param name="query">câu truy vấn</param>
        /// <returns>DataTable</returns>
        public DataTable ExecuteSelect(string query)
        {
            if (!this.Open())
            {
                Connection.Open();
            }
            SqlCommand cmd = new SqlCommand(query, Connection);
            DataTable table = new DataTable();
            SqlDataAdapter DataAdapter = new SqlDataAdapter(cmd);
            DataAdapter.Fill(table);
            Connection.Close();
            DataAdapter.Dispose();
            return table;
        }

    }
}
